/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.persistence.hibernate.criteria.field;

import java.util.Date;
import java.util.Map;

import com.genia.toolbox.basics.manager.CollectionManager;
import com.genia.toolbox.persistence.hibernate.bean.impl.QueryableDisplayObject;
import com.genia.toolbox.persistence.hibernate.criteria.HibernateCriteria;
import com.genia.toolbox.persistence.hibernate.manager.HibernatePersistenceManager;

/**
 * this field represents a constant value.
 */
public class HibernateConstantField
    implements HibernateField
{

  /**
   * static variable used to generate a new alias for each constant element.
   */
  private static long nbValue = 0;



  /**
   * returns a new unique value to generate a new alias for each constant
   * element.
   * 
   * @return a new unique value to generate a new alias for each constant
   *         element
   */
  private static long getNextValue()
  {
    synchronized (HibernateConstantField.class) {
      return nbValue++;
    }
  }

  /**
   * the value this field represents.
   */
  private final transient Object value;

  /**
   * the alias of this element.
   */
  private final transient String alias;



  /**
   * returns an escaped version of the current Field.
   * 
   * @return an escaped version of the current Field
   * @see com.genia.toolbox.persistence.hibernate.criteria.field.HibernateField#escapedField()
   */
  public HibernateField escapedField()
  {
    if (value instanceof String) {
      return new HibernateConstantField(escapeString((String) value));
    }
    return this;
  }



  /**
   * escape the value with the '\' character.
   * 
   * @param value
   *          the value to escape
   * @return the escaped value
   */
  private String escapeString(String value)
  {
    StringBuilder stringBuilder = new StringBuilder();
    for (char character : value.toCharArray()) {
      switch (character) {
        case HibernatePersistenceManager.ESCAPE_CHARACTER:
        case '%':
        case '_':
          stringBuilder.append(HibernatePersistenceManager.ESCAPE_CHARACTER);
        default:
          stringBuilder.append(character);
      }
    }
    return stringBuilder.toString();
  }



  /**
   * the default constructor.
   * 
   * @param value
   *          the value this field represents
   */
  public HibernateConstantField(final Object value)
  {
    this.value = value;
    this.alias = "v" + getNextValue();
  }



  /**
   * returns if this <code>Field</code> is an aggregate.
   * 
   * @return <code>true</code> if this <code>Field</code> is an aggregate,
   *         <code>false</code> otherwise.
   */
  public boolean isAggregate()
  {
    return false;
  }



  /**
   * append to stringBuilder the part of the query represented by this object.
   * 
   * @param canHaveParameter
   *          can this part of the query use named parameters?
   * @param collectionManager
   *          The <code>CollectionManager</code> that allow us to perform
   *          joins
   * @param criteria
   *          the <code>HibernateCriteria</code> the represents the all query
   * @param stringBuilder
   *          the <code>StringBuilder</code> to append to.
   * @param queryableDisplayObject
   *          the <code>DisplayObject</code> that allows to convert this
   *          <code>Queryable</code> to a <code>String</code>
   */
  public void appendQuery(final boolean canHaveParameter, final CollectionManager collectionManager, final HibernateCriteria<?> criteria, final StringBuilder stringBuilder,
      final QueryableDisplayObject queryableDisplayObject)
  {
    if (canHaveParameter) {
      stringBuilder.append(":");
      stringBuilder.append(alias);
    }
    else {
      if (value instanceof Number) {
        stringBuilder.append(value.toString());
      }
      else if (value instanceof Date) {
        stringBuilder.append("new java.util.Date(");
        stringBuilder.append(String.valueOf(((Date) value).getTime()));
        stringBuilder.append("l)");
      }
      else {
        stringBuilder.append('\'');
        stringBuilder.append(escapeForHibernate(value));
        stringBuilder.append('\'');
      }
    }
  }



  /**
   * Escape the value passed in parameter to a String that is accepted in a HQL
   * query.
   * 
   * @param value
   *          the value to escape
   * @return the escaped representation of <code>value</code>
   */
  public String escapeForHibernate(final Object value)
  {
    return value.toString().replace("'", "''");
  }



  /**
   * Fill the parameters <code>Map</code> with the constants elements of this
   * query.
   * 
   * @param parameters
   *          the <code>Map</code> to be filled
   */
  public void fillParameters(final Map<String, Object> parameters)
  {
    parameters.put(alias, value);
  }

}
